<template>
  <div>
    <!-- 搜索卡片 -->
    <el-card class="box-card">
      <el-row :gutter="10" style="padding: 5px 5px; line-height: 28px" align="middle">
        <el-col :sm="5" :md="4" style="text-align: right">{{ $t('common.searchKey') }}</el-col>
        <el-col :sm="19" :md="12" style="text-align: left">
          <el-input
            v-model="searchKey"
            @keyup.enter="handleSearch"
            :placeholder="$t('monitor.ipAddr') + '/' + $t('common.remark')"
          />
        </el-col>
        <el-col :sm="24" :md="8" style="text-align: right">
          <div style="margin-right: -5px">
            <el-button @click="handleSearch" type="primary" size="small" plain
              ><Icon icon="ic:outline-search" /><span>{{ $t('common.query') }}</span></el-button
            >
            <el-button @click="searchKey = ''" type="info" size="small" plain>
              <Icon icon="icon-park-solid:clear-format" /><span>{{
                $t('common.reset')
              }}</span></el-button
            >
            <el-button
              type="success"
              size="small"
              plain
              v-if="hasAuth('add')"
              @click="openDialog('create', null)"
            >
              <Icon icon="material-symbols:add-circle-rounded" /><span>{{ $t('common.add') }}</span>
            </el-button>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 搜索列表卡片 -->
    <el-card class="formcard">
      <!-- 搜索結果表格 -->
      <el-table
        :data="tableView"
        tooltip-effect="light"
        style="width: 100%; border-color: #a0cfff"
        :max-height="tableHeight"
        stripe
        class="loginList"
        :header-cell-style="{
          background: 'var(--el-color-primary-light-9)',
          color: '#409eff'
        }"
      >
        <el-table-column
          prop="ipAddr"
          :label="$t('monitor.ipAddr')"
          show-overflow-tooltip
          min-width="120"
        />
        <el-table-column
          prop="type"
          :label="$t('monitor.type')"
          show-overflow-tooltip
          min-width="100"
        >
          <template #default="{ row }">
            <span v-if="row.type == 1">{{ $t('monitor.type1') }}</span>
            <span v-if="row.type == 2">{{ $t('monitor.type2') }}</span>
          </template></el-table-column
        >
        <el-table-column
          prop="staus"
          :label="$t('common.status')"
          show-overflow-tooltip
          min-width="100"
        >
          <template #default="{ row }">
            <el-switch v-model.number="row.status" :active-value="1" :inactive-value="0" disabled />
          </template>
        </el-table-column>

        <el-table-column
          prop="remark"
          :label="$t('common.remark')"
          show-overflow-tooltip
          min-width="150"
        />

        <el-table-column
          prop="updateBy"
          :label="$t('monitor.editBy')"
          show-overflow-tooltip
          min-width="120"
        />
        <el-table-column
          prop="updateTime"
          :label="$t('group.updateDate')"
          show-overflow-tooltip
          min-width="150"
        />

        <el-table-column fixed="right" :label="$t('common.operation')" width="120">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              plain
              circle
              :title="$t('common.modify')"
              v-if="hasAuth('edit')"
              @click="openDialog('update', row)"
            >
              <el-icon>
                <Edit />
              </el-icon>
            </el-button>
            <el-button
              v-if="hasAuth('delete')"
              type="danger"
              size="small"
              plain
              circle
              :title="$t('common.delete')"
              @click="delIp(row.id)"
            >
              <el-icon>
                <Delete />
              </el-icon>
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分頁器 -->
      <div class="demo-pagination-block">
        <el-pagination
          v-model:currentPage="param.pageNo"
          v-model:page-size="param.pageSize"
          @current-change="changePage"
          @size-change="changePageSize"
          :page-sizes="pageSizes"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalCount"
        />
      </div>
    </el-card>

    <!-- 對話框 -->
    <el-dialog v-model="dialogFormVisible" :title="dialogTitle[dialogStatus]" width="50%" draggable>
      <el-form
        ref="formRef"
        :model="dialogForm"
        :rules="dialogRules"
        label-position="right"
        label-width="120px"
        style="padding-right: 10px"
      >
        <el-form-item :label="$t('monitor.ipAddr')" prop="ipAddr" class="requireLabel">
          <el-input
            v-model="dialogForm.ipAddr"
            required
            :placeholder="$t('common.inputText') + $t('monitor.ipAddr')"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
        <el-form-item :label="$t('monitor.type')" prop="type" class="requireLabel">
          <el-radio-group v-model="dialogForm.type">
            <el-radio :label="1">{{ $t('monitor.type1') }}</el-radio>
            <el-radio :label="2">{{ $t('monitor.type2') }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t('common.status')" prop="status" class="requireLabel">
          <el-switch v-model.number="dialogForm.status" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item :label="$t('common.remark')" prop="remark" class="normal_label">
          <el-input
            type="textarea"
            v-model="dialogForm.remark"
            :placeholder="$t('common.inputText') + $t('common.remark')"
            :autosize="{ minRows: 2 }"
            :rows="4"
            maxlength="255"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer" style="text-align: center">
          <el-button type="primary" plain @click="saveIp">
            <el-icon><Select /></el-icon>&nbsp;{{ $t('common.save') }}
          </el-button>
          <el-button type="info" plain @click="dialogFormVisible = false" style="margin-left: 30px">
            <el-icon> <Close /> </el-icon>&nbsp;{{ $t('common.giveUp') }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { reactive, toRefs, onMounted, onActivated, ref } from 'vue'
import { Edit, Delete, Select, Close } from '@element-plus/icons-vue'
import { getIpStrategy, saveIpStrategy, delIpStrategy } from '@/api/monitor'
import { Paging } from '@/config/public'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { getUserPageAuth } from '@/api/system/authority'
import { hasElementAuth } from '@/utils/authority'
import { useI18n } from '@/hooks/web/useI18n'
export default {
  // name: 'Restrictlogin',
  components: {
    Edit,
    Delete,
    Select,
    Close
  },
  props: {},
  setup() {
    const router = useRouter()
    const formRef = ref()
    const { t } = useI18n()
    const state = reactive({
      searchKey: '',
      // 表格數據
      tableView: [],
      tableHeight: 400,
      // 分頁相關屬性
      totalCount: 0,
      pageSizes: Paging.sizes,
      param: {
        key: '',
        pageNo: 1,
        pageSize: Paging.defaultSize,
        params: {
          Q_status_I_LT: 4
        },
        sortField: '',
        sortOrder: ''
      },
      // 對話框綁定的數據
      dialogFormVisible: false,
      dialogTitle: {
        create: t('common.add') + ' ' + t('monitor.ipStrategy'),
        update: t('common.modify') + ' ' + t('monitor.ipStrategy')
      },
      dialogStatus: '',
      dialogForm: {
        ipAddr: '',
        remark: '',
        status: 1,
        type: 1
      },
      pageAuths: [{}],
      dialogRules: {
        ipAddr: [
          {
            required: true,
            message: t('common.inputText') + t('monitor.ipAddr'),
            trigger: 'blur'
          },
          {
            pattern: /^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$/,
            message: t('monitor.ipAddr') + t('company.errFormat'),
            trigger: 'blur'
          }
        ]
      }
    })
    onMounted(async () => {
      init()
      let muid = router.currentRoute.value.meta.id as string
      state.pageAuths = (await getUserPageAuth(muid)).data
    })
    onActivated(async () => {})
    const methods = {
      // 是否有权限
      hasAuth(key) {
        return hasElementAuth(state.pageAuths, key)
      },
      changePage(page) {
        state.param.pageNo = page
        init()
      },
      changePageSize(pageSize) {
        state.param.pageSize = pageSize
        state.param.pageNo = 1
        init()
      },
      // 打開對話框
      openDialog(type, row) {
        state.dialogForm = {
          ipAddr: '',
          remark: '',
          status: 1,
          type: 1
        }
        if (type == 'update') {
          state.dialogForm.ipAddr = row.ipAddr
          state.dialogForm.remark = row.remark
          state.dialogForm.status = row.status
          state.dialogForm.type = row.type
          state.dialogForm.id = row.id
        }
        state.dialogStatus = type
        state.dialogFormVisible = true
      },
      // 新增或編輯白名單
      saveIp() {
        formRef.value.validate(async (valid) => {
          if (valid) {
            await saveIpStrategy(state.dialogForm).then((res) => {
              if (res) {
                ElMessage.success(t(res.message))
                state.dialogFormVisible = false
                init()
              }
            })
          }
        })
      },
      // 刪除白名單
      delIp(id) {
        ElMessageBox.confirm(t('common.delMessage'), t('common.warning'), {
          confirmButtonText: t('common.ok'),
          cancelButtonText: t('common.cancel'),
          type: 'warning'
        }).then(async () => {
          await delIpStrategy(id).then((res) => {
            if (res) {
              ElMessage.success(t(res.message))
              init()
            }
          })
        })
      },
      // 搜索
      handleSearch() {
        state.param.key = state.searchKey
        init()
      }
    }
    //渲染页面的接口
    const init = async () => {
      await getIpStrategy(state.param).then((res) => {
        if (res) {
          state.tableView = res.result.data
          state.totalCount = res.result.totalCount
        }
      })
    }
    return {
      formRef,
      ...toRefs(state),
      ...methods
    }
  }
}
</script>

<style lang="less" scoped>
// 搜索卡片樣式
:deep(.el-card__header) {
  border-bottom: 0;
  box-sizing: border-box;
}
:deep(.el-form-item__error) {
  left: 12px;
}

//搜索條樣式
.input-with-select {
  width: 50%;
  margin-left: auto;
  margin-right: auto;
}
:deep(.el-input-group__append) {
  background-color: #ecf5ff;
  border-color: #a0cfff;
  color: #409eff;
  box-shadow: #409eff;
  cursor: pointer;
}
:deep(.el-input-group__append):hover {
  background-color: #ecf5ff;
  border-color: #409eff !important;
  color: #409eff;
  box-shadow: #409eff;
  cursor: pointer;
}
:deep(.el-input) {
  border-color: #a0cfff;
  font-size: 12px;
}
// 公司列表卡片樣式
.formcard {
  margin-top: 8px;
}
// 公司列表樣式
.loginList {
  font-size: 12px;
}
// 新增白名单对话框
.dialogLabel1 {
  margin-left: 20px;
}
.dialogLabel2 {
  margin-left: auto;
  margin-right: auto;
}
.dialogInput1 {
  margin-left: auto;
  margin-right: auto;
}
.dialogInput2 {
  margin-left: auto;
  margin-right: auto;
}
:deep(.el-input__wrapper) {
  font-size: 12px;
}

:deep(.el-textarea__inner) {
  font-size: 12px;
}

// 分頁器樣式
.demo-pagination-block {
  display: flex;
  justify-content: center;
  justify-items: center;
  margin-top: 20px;
  margin-bottom: 20px;
}
:deep(.el-pager li) {
  font-size: 12px;
  height: 28px;
  margin-top: -1px;
}
:deep(.el-pagination span:not([class*='suffix'])) {
  font-size: 12px;
}
.require_input,
.normal_label {
  position: relative;
  margin-left: 10px;
}
:deep(.requireLabel) {
  margin-left: 10px;
}
</style>
